#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import cgi
import datetime
import os
import lib
import logging
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.ext import db
from google.appengine.api import datastore_errors
from google.appengine.ext.webapp import template
from lib import llhandler
from lib.workflowManager import WorkflowManager
from model.models import *
class ListRequestsHandler(llhandler.PSHandler):
	
	
	def internal_get(self):
		
		self.add("requests",PSRequest.all().order('-created'))
		self.render('requests_list')
		#self.render('index')
		#self.base_auth()
		#self.get_internal()
		#user_logout = users.create_logout_url("/eventos/")
		#self.response.out.write("<a href=\"%s\">Logout</a>." %user_logout)
	
	def internal_post(self):
		self.internal_get()
		
class CreateRequestHandler(llhandler.PSHandler):
  
	def get(self,wf_id):
	  self.auth_check()
	  self.internal_get(wf_id)
	
	def post(self,wf_id):
	  self.auth_check()
	  self.internal_post(wf_id)
	
	def internal_get(self,wf_id):
	  wf = PSWorkflow.get(db.Key(encoded=wf_id))
	  if wf is None:
	    self.set_flash("Non existing workflow")
	    self.redirect("/workflows/")
	    return
	  self.add('workflow',wf)
	  self.render('request_new')
	  
	def internal_post(self,wf_id):
	  wf = PSWorkflow.get(db.Key(encoded=wf_id))
	  if wf is None:
	    self.set_flash("Non existing workflow")
	    self.redirect("/workflows/")
	    return
	  
	  try:
	    
	    psrequest = PSRequest(comment=self.request.get('comment'),status="pending")
	    psrequest.requestor = self.user
	    psrequest.workflow = wf
	    psrequest.name = self.request.get('name')
	    psrequest.origin = self.request.get('origin')
	    psrequest.destination = self.request.get('destination')
	    psrequest.files_changed = self.request.get_all('files_changed_values')
	    psrequest.required_commands = self.request.get_all('required_commands_values')
	    
	    psrequest.put()
	    self.prepare_request_for_workflow(psrequest,wf)
	  except Exception, e:
	    self.set_flash('Could not create request:' + str(e),'error')
	    self.internal_get(wf_id)
	    return
	  self.set_flash('Request Successfully created');
	  self.redirect('/requests/'+str(psrequest.key()))
	 
	def prepare_request_for_workflow(self,request,workflow):
	  
	  elements = workflow.elements.order('priority')
	  #elements.sort(cmp=lambda x,y: cmp(x.priority,y.priority))
	  for element in elements:
	    step = PSStep()
	    step.workflow_element = element
	    step.request = request
	    step.put()
	    request.pending_steps.append(step.key())
	  request.put()
	  WorkflowManager().requestCreated(request)
	  
class ShowRequestHandler(llhandler.PSHandler):
	
	def get(self,req_id):
	  self.auth_check()
	  self.internal_get(req_id)
	  
	def internal_get(self,req_id):
		request = PSRequest.get(db.Key(encoded=req_id))
		pending_steps = PSStep.get(request.pending_steps)
		passed_steps = PSStep.get(request.passed_steps)
		self.add("request",request)
		self.add("pending_steps",pending_steps)
		self.add("passed_steps",passed_steps)
		self.render('request_show')


def main():
  logging.getLogger().setLevel(logging.DEBUG)
  application = webapp.WSGIApplication([('/requests/create_for_workflow/(\S+)',CreateRequestHandler),
					('/requests/(\S+)', ShowRequestHandler),
					('/requests/', ListRequestsHandler)],
                                       debug=True)
  util.run_wsgi_app(application)


if __name__ == '__main__':
  main()
